package com.example.recyclerview;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.recyclerview.databinding.ActivityMainBinding;
import com.google.android.material.snackbar.Snackbar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private FruitAdapter adapter;
    private int position = -1;
    private boolean isAdd = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initData();
        initRecyclerView();

        // 设置FAB的点击事件监听
        binding.fabAdd.setOnClickListener(view -> {
//            Snackbar.make(view, "添加一个水果信息", Snackbar.LENGTH_LONG).setAction("Action", null).show();
//            Fruit fruit = new Fruit("新增苹果", R.drawable.apple);
//            adapter.addData(fruits.size(), fruit);
            isAdd = true;
            position = fruits.size();
            launcher.launch(new Intent(MainActivity.this, FruitAddOrUpdateActivity.class));
        });
    }

    private void initRecyclerView() {
        // 设置布局管理器，线性布局器
        binding.rvFruit.setLayoutManager(new LinearLayoutManager(this));
        // 2列的网格布局器
//        binding.rvFruit.setLayoutManager(new GridLayoutManager(this, 2));
        // 设置分割线
        binding.rvFruit.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        // 设置动画
        binding.rvFruit.setItemAnimator(new DefaultItemAnimator());
        // 设置RecyclerView的适配器
        adapter = new FruitAdapter(fruits, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 设置item点击事件监听
                final FruitAdapter.ViewHolder viewHolder = (FruitAdapter.ViewHolder) view.getTag();
                position = viewHolder.getAdapterPosition();
                adapter.setSelectedIndex(position);
                final Fruit fruit = fruits.get(position);
                Snackbar.make(view, String.format(Locale.CHINA, "点击了第%d行的%s", position + 1, fruit.getTitle()),
                        Snackbar.LENGTH_SHORT).show();

//                Intent intent = new Intent(MainActivity.this, FruitAddOrUpdateActivity.class);
//                final Bundle bundle = new Bundle();
//                bundle.putSerializable("fruit", fruit);
//                intent.putExtras(bundle);
//                launcher.launch(intent);

                isAdd = false;
            }
        });
        binding.rvFruit.setAdapter(adapter);

        // 长按删除
        adapter.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                final FruitAdapter.ViewHolder viewHolder = (FruitAdapter.ViewHolder) view.getTag();
                final int position = viewHolder.getAdapterPosition();
                Snackbar.make(view, "确认删除?", Snackbar.LENGTH_LONG)
                        .setAction("删除", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // 自定义删除数据的方法： 删除fruits列表中的position位置的数据、更新adapter
                                adapter.removeData(position);
                            }
                        }).show();
                return true;
            }
        });

        // item滑动删除、长按拖曳
        new ItemTouchHelper(new ItemTouchHelper.Callback() {
            //左滑、右滑删除
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                final int position = viewHolder.getAdapterPosition();
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("删除")
                        .setMessage("确认删除？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            adapter.removeData(position);
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                adapter.notifyItemChanged(which);
                                dialog.dismiss();
                            }
                        }).show();
            }
            // 长按拖曳
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView,
                                  @NonNull RecyclerView.ViewHolder viewHolder,
                                  @NonNull RecyclerView.ViewHolder target) {
                final int startPos = viewHolder.getAdapterPosition();
                final int endPos = target.getAdapterPosition();
                if (startPos < endPos) {
                    for (int i = startPos; i < endPos; i++) {
                        Collections.swap(fruits, i, i + 1);
                    }
                } else {
                    for (int i = startPos; i > endPos; i--) {
                        Collections.swap(fruits, i, i - 1);
                    }
                }
                adapter.notifyItemMoved(startPos, endPos);
                return true;
            }
            // 设置拖拽方向、滑动方向
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView,
                                        @NonNull RecyclerView.ViewHolder viewHolder) {
                int dragFlags = 0;
                int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager ||
                        recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager){
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT;
                }
                else {
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                }
                return makeMovementFlags(dragFlags, swipeFlags);
            }
        }).attachToRecyclerView(binding.rvFruit);
    }

    private final List<Fruit> fruits = new ArrayList<>();
    private final List<Fruit> fruitList = new ArrayList<Fruit>() {
        {
            add(new Fruit("苹果", R.drawable.apple));
            add(new Fruit("香蕉", R.drawable.banana));
            add(new Fruit("橙子", R.drawable.orange));
            add(new Fruit("樱桃", R.drawable.cherry));
            add(new Fruit("芒果", R.drawable.mango));
            add(new Fruit("梨子", R.drawable.pear));
            add(new Fruit("草莓", R.drawable.strawberry));
            add(new Fruit("菠萝", R.drawable.pineapple));
            add(new Fruit("西瓜", R.drawable.watermelon));
            add(new Fruit("葡萄", R.drawable.grape));
        }
    };

    // 初始化数据
    private void initData() {
        fruits.clear();
//        for (int i = 0; i < 10; i++) {
//            fruits.addAll(fruitList);
//        }
//        Collections.shuffle(fruits);

        // 使用strings.xml中定义的数组进行初始化
        String[] titles = getResources().getStringArray(R.array.fruit_title_array);
        String[] descriptions = getResources().getStringArray(R.array.fruit_description_array);
        TypedArray images = getResources().obtainTypedArray(R.array.fruit_image_array);

        for (int i = 0; i < 10; i++) {
            fruits.add(new Fruit(titles[i], images.getResourceId(i, 0), descriptions[i]));
        }
        Collections.shuffle(fruits);
        images.recycle();  // TypedArray使用后要回收
    }

    private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result != null && result.getData() != null) {
                        final Bundle extras = result.getData().getExtras();
                        if (isAdd) {
                            adapter.addData(position, (Fruit) extras.getSerializable("fruit"));
                        } else {
                            adapter.updateData(position, (Fruit) extras.getSerializable("fruit"));
                        }
                    }
                }
            });
}